<?php

namespace App;



/**
 * App\Post
 *
 * @property int $id
 * @property string $title
 * @property string $content 内容
 * @property int $user_id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereContent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Post whereUserId($value)
 * @mixin \Eloquent
 */
class Post extends Model
{
    //如果模型名和表名不一致
    //protected $table = '表名';

    //protected $guarded; //不可以注入的字段
    //protected $fillable = ['title','content']; //可以注入的数据字段

    protected $table = "posts";

    protected $guarded = [];

    //用户关联  文章是属于哪个用户的

    public function user(){

        return $this->belongsTo("App\User","user_id","id");
    }
    //一对多评论模型

    public function comments(){
        return $this->hasMany(Comment::class,'post_id','id')->orderByDesc("created_at");
    }
    //文章的所有赞
    public function zans(){
        return $this->hasMany(\App\Zan::class,"posd_id",'id');
    }
    //和用户进行关联(这篇文章对某一个用户id 是否有赞)
    //判断一个用户是否已经给这篇文章点赞了

    public function zan($user_id){
        // return $this->hasOne('App\Zan')->where('user_id',$user_id);
        //laravel_jianshu
        //select exists(select * from `zans` where `zans`.`posd_id` = 104 and `zans`.`posd_id` is not null and `user_id` = 101) as `exists`
        return $this->hasOne(\App\Zan::class,'posd_id','id')->where('user_id', $user_id);
//        return $this->hasOne(\App\Zan::class,'posd_id','id')->where('user_id', $user_id)->exists();
    }

}
